import Vue from 'vue'
import TopLoading from '@/components/TopLoading'

const LoadingContructor = Vue.extend(TopLoading)

export const topLoadingbind = (el, binding) => {
  if (binding.value) {
    if (!el.__top_loading_start__) {
      let instance = new LoadingContructor()
      let referenceElement = el.firstElementChild
      instance.$mount()
      if (referenceElement) {
        el.insertBefore(instance.$el, referenceElement)
      } else {
        el.appendChild(instance.$el)
      }
      el.__top_loading_start__ = true
    }
  } else {
    if (el.__top_loading_start__) {
      setTimeout(() => {
        el.removeChild(el.firstElementChild)
        el.__top_loading_start__ = false
      }, 0)
    }
  }
}

export default {
  install (Vue) {
    Vue.directive('top-loading', topLoadingbind)
  }
}
